package com.atguigu.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet(urlPatterns = "/Servlet10RequestParam")
public class Servlet10RequestParam extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 超链接发送的是 GET 请求，在 doGet() 方法中接收请求参数
        // /Servlet10RequestParam?userName=tom2024&userAge=35
        // 根据请求参数的名字，获取请求参数的值（一个名字携带一个值）
        String userName = request.getParameter("userName");
        String userAge = request.getParameter("userAge");

        // 获取多个同名请求参数的值（一个名字对应多个值）
        // &team=Germon&team=France&team=China
        String[] teams = request.getParameterValues("team");

        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("userName = " + userName + "<br/>");
        response.getWriter().write("userAge = " + userAge + "<br/>");
        for (String team : teams) {
            response.getWriter().write("team = " + team + "<br/>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 根据请求参数的名字，获取请求参数的值（一个名字携带一个值）
        String userName = request.getParameter("userName");
        String userAge = request.getParameter("userAge");

        // 获取多个同名请求参数的值（一个名字对应多个值）
        // &team=Germon&team=France&team=China
        String[] userHobbies = request.getParameterValues("userHobby");

        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("userName = " + userName + "<br/>");
        response.getWriter().write("userAge = " + userAge + "<br/>");
        for (String userHobby : userHobbies) {
            response.getWriter().write("userHobby = " + userHobby + "<br/>");
        }
    }
}
